<?php

namespace app\web\controller;

use app\common\controller\Frontend;
use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\Storehouse;
use app\common\model\supplier\Supplier;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use think\Validate;
use app\common\model\purchase\Order;


class Purchase extends Frontend
{

    protected $noNeedLogin = 'login';
    protected $noNeedRight = '*';
    protected $layout = '';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Goods;
    }
    public function index(){
        $where = [];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
//        $where['storehouse_id'] = $storehouse_id;
        $where['pg.storehouse_id'] = $storehouse_id;
        $list = Db::name('purchase_goods')
            ->alias('pg')
            ->where($where)
            ->field('pg.id,place_origin,specs,title,goods_num,operator,company,g.number,needtime,unit,pg.createtime,s.nickname as snick,pg.status,h.name')
            ->join('zax_goods g','pg.goods_id = g.id')
            ->join('supplier s','g.supplier_id = s.id','LEFT')
            ->join('storehouse h','pg.storehouse_id = h.id')
            ->limit(0,10)
            ->order('pg.id','DESC')
            ->select();

        $goods_status = $this->model->goods_status();
        foreach ($list as $k=>$v){
            $list[$k]['ystatus'] = $v['status'];
            $list[$k]['status'] = $goods_status[$v['status']];
        }

        $total = Db::name('purchase_goods')
            ->alias('pg')
            ->where($where)
            ->field('pg.id,place_origin,specs,title,goods_num,operator,company,g.number,needtime,unit,pg.createtime,s.nickname as snick,pg.status,h.name')
            ->join('zax_goods g','pg.goods_id = g.id')
//                ->join('admin a','pg.admin_id = a.id')
            ->join('supplier s','g.supplier_id = s.id','LEFT')
            ->join('storehouse h','pg.storehouse_id = h.id')
            ->count();
        $this->assign('list',$list);
        $this->assign('total',$total);
        $this->assign('purl','users');
        return $this->view->fetch();
    }
    public function getpurchase(){
        $page = input('page/d',1);
        $pagesize = input('pagesize/d',10);
        $where = [];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
//        $where['storehouse_id'] = $storehouse_id;
        $where['storehouse_id'] = $storehouse_id;
        $list = Db::name('purchase_goods')
            ->alias('pg')
            ->where($where)
            ->field('pg.id,place_origin,specs,title,goods_num,operator,company,g.number,needtime,unit,pg.createtime,s.nickname as snick,pg.status,h.name')
            ->join('zax_goods g','pg.goods_id = g.id')
            ->join('supplier s','g.supplier_id = s.id','LEFT')
            ->join('storehouse h','pg.storehouse_id = h.id')
            ->limit($page*$pagesize,$pagesize)
            ->order('pg.id','DESC')
            ->select();

        $goods_status = $this->model->goods_status();
        foreach ($list as $k=>$v){
            $list[$k]['ystatus'] = $v['status'];
            $list[$k]['status'] = $goods_status[$v['status']];
        }
        $this->success('','',$list);
    }

    public function confirm(){
        $supplier_id = input('s_id/d',0);
        $cart_ids = input('cart_ids');
        $tax = input('tax',0);

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        $ids = explode('-',$cart_ids);
        $supplier = new Supplier();
        $row =  $supplier->where(array('id'=>$supplier_id))->find();
        if(empty($row)){
            $this->error('未选择供应商');
        }
        $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,number,g.storehouse_id,title,place_origin,specs,goods_num,unit,unit_price,tax,remark,a.nickname,g.purchase_order_id,g.status')
            ->alias('g')
            ->where(array('g.id'=>array('in',$ids)))
            ->join('goods go','g.goods_id = go.id')
            ->join('admin a','g.admin_id = a.id')
            ->select();
        if ($this->request->isAjax()) {
            if(empty(session('admin')['storehouse_id'])){
                $this->error('没有归属仓库,不允许创建');
            }
            $explain = input('explain');
            $tax = input('tax/d',0);
            $datas = input('datas/a');

            $model = new Order;
            $num = $model->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $cdata = array(
                'supplier_id'=>$row['id'],
                'tax'=>$tax,
                'storehouse_id'=>session('admin')['storehouse_id'],
                'explain'=>$explain,
                'number' =>'JD-T-'.date('Y-m-d').'-'.getnumber($num),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
            );
            //自检开始
            $order_goods_total = 0;
            $order_price = 0;
            foreach ($list as $k=> $v){
                if($v['status'] >1){
                    $this->error($v['title'].'状态异常');
                }
                foreach ($datas as $val){
                    if($v['id'] == $val['id']){
                        $order_goods_total += $v['goods_num'];
                        $order_price += $val['ht_price']*$v['goods_num'];
                        $list[$k]['ht_price'] = $val['ht_price'];
                    }
                }
            }

            $cdata['order_goods_total'] = $order_goods_total;
            $cdata['order_price'] = $order_price;
            Db::startTrans();
            try{
                $model->save($cdata);
                if(!$model->id){
                    Db::rollback();
                    throw new Exception('添加失败');
                }


                foreach ($list as $v){
                        if(isset($v['ht_price'])){
                            $data[] = array(
                              'goods_id'=>$v['goods_id'],
                            );
                            $data = array(
                                'tax'=>$tax,
                                'unit_price'=>$v['ht_price']/(1+$tax/100),
                                'ht_price' => $v['ht_price'],
//                                'remark'=>$v['remark'],
                                'status'=>2,
                                'purchase_order_id'=>$model->id,
                            );
                            $goodsmodel = new \app\common\model\purchase\Goods;
                           $res = $goodsmodel->save($data,array('id'=>$v['id']));
                            if(!$res){
                                Db::rollback();
                                throw new Exception('添加失败');
                            }
                        }
                }
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


        $allnum = 0;
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $allnum+=$v['goods_num'];
        }

        $this->assign('tax',$tax);
        $this->assign('allnum',$allnum);
        $this->assign('list',$list);
        $this->assign('supplier_id',$supplier_id);
        $this->assign('cart_ids',$cart_ids);
        $this->assign('ids',$ids);
        $this->assign('row',$row);
        $this->assign('nickname',session('admin')['nickname']);
        $this->assign('gname',$group['name']);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }

    //选择商品
    public function choose(){
        $where = [];
        $keywords = input('keywords');
        if(!empty($keywords)){
            $where['title'] = array('like','%'.$keywords.'%');
        }
        $goodmodel = new Goods();
        $list = $goodmodel
            ->where($where)
            ->with('brands')
            ->order('weigh','desc')
            ->limit(0,10)
            ->select();
        $total = $goodmodel->where($where)->count();
        foreach ($list as $row) {
            $row->visible(['id','title','place_origin','number','unit','createtime','status','price','specs','stock','new_cost_price','weigh']);
            $row->visible(['brands']);
            $row->getRelation('brands')->visible(['name']);
        }

        $list = collection($list)->toArray();
        //获取默认仓库或者所属仓库
        if(session('admin')['storehouse_id'] >0){
            $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
        }else{
            $this->error('无归属仓库');
            $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
        }

        $numbers = [];
        foreach ($list as &$v){
            $numbers[] = $v['number'];
            $house = new GoodsHouseStock();
            $v['stock'] = $house->getstock($v['id'],$hrow['id']);
        }
        $prices = $this->getprice(implode(',',$numbers),$hrow['code']);

        foreach ($list as &$v){
            $v['price'] = 0;
        }

        $this->assign('keywords',$keywords);
        $this->assign('list',$list);
        $this->assign('total',$total);
        $this->assign('purl','index');
        return $this->view->fetch();
    }
    public function add(){
        $ids = input('ids/d',0);
        $row = Goods::find($ids);
        if($this->request->isAjax()){
            if(empty($row)){
                $this->error('暂无商品');
            }
            $goods_num = input('num/d',0);
            if($goods_num <1){
                $this->error('请购数量必须大于1');
            }
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $data = array(
              'storehouse_id'=>input('storehouse_id/d',0),
              'goods_num'=>$goods_num,
              'goods_id'=>$ids,
              'needtime'=>strtotime(input('needtime','')),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
              'createtime'=>time()
            );
            $res = Db::name('purchase_goods')->insert($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }


        if(session('admin')['storehouse_id'] > 0){
            $how = Storehouse::find(session('admin')['storehouse_id']);
            $houses[] = $how;
        }else{
            $houses = Storehouse::select();
        }


        $model = new GoodsHouseStock;
        $stock = $model->getstock($ids,session('admin')['storehouse_id']);
        $this->assign('stock',$stock);
        $this->assign('row',$row);
        $this->assign('houses',$houses);

        return $this->view->fetch();
    }


}
